package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.entity.Visit;
import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.service.VisitService;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.UserService;
import cn.edu.buu.hospital.service.DoctorService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 预约排班控制类
 * 负责处理医院预约排班的相关HTTP请求，包括新增排班、查询排班、编辑排班、删除排班等功能
 */
@Controller
@RequestMapping("/visit")
public class VisitController {
    @Autowired
    private VisitService visitService; // 预约排班服务，处理排班相关业务逻辑
    
    @Autowired
    private DepartmentService departmentService; // 科室服务，处理科室相关业务逻辑
    
    @Autowired
    private UserService userService; // 用户服务，处理用户相关业务逻辑
    
    @Autowired
    private DoctorService doctorService; // 医生服务，处理医生相关业务逻辑

    /**
     * 跳转到新增排班页面
     * @param model 模型对象，用于传递数据到视图
     * @return 新增排班页面的视图路径
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        // 添加科室列表到model中，用于页面选择
        model.addAttribute("departmentList", departmentService.findAll());
        return "backend/visit/add"; // 返回新增排班页面
    }

    /**
     * 新增排班
     * @param visit 排班实体对象，包含排班相关信息
     * @param model 模型对象，用于传递数据到视图
     * @return 成功则重定向到排班列表页面，失败则返回新增页面
     */
    @PostMapping("/add")
    public String add(Visit visit, Model model) {
        try {
            // 添加详细的日志打印，查看接收到的参数值
            System.out.println("====== 开始新增排班 ======");
            System.out.println("接收到的Visit对象: " + visit);
            System.out.println("maxNum值: " + visit.getMaxNum());
            System.out.println("deptId值: " + visit.getDeptId());
            System.out.println("doctorName值: " + visit.getDoctorName());
            System.out.println("visitDate值: " + visit.getVisitDate());
            System.out.println("timeSlot值: " + visit.getTimeSlot());
            
            // 直接从request获取参数值，确保能获取到正确的日期和时段信息
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String visitDateStr = request.getParameter("visitDate");
            String timeSlotStr = request.getParameter("timeSlot");
            String maxNumStr = request.getParameter("maxNum");
            
            System.out.println("直接从request获取的visitDate: " + visitDateStr);
            System.out.println("直接从request获取的timeSlot: " + timeSlotStr);
            
            // 验证并构建visitPeriod - 修复排班时段验证逻辑
            if (visitDateStr == null || visitDateStr.isEmpty()) {
                model.addAttribute("error", "新增失败: 排班日期不能为空");
                model.addAttribute("visit", visit);
                model.addAttribute("departmentList", departmentService.findAll());
                return "backend/visit/add";
            }
            
            if (timeSlotStr == null || timeSlotStr.isEmpty()) {
                model.addAttribute("error", "新增失败: 排班时段不能为空");
                model.addAttribute("visit", visit);
                model.addAttribute("departmentList", departmentService.findAll());
                return "backend/visit/add";
            }
            
            // 构建完整的排班时段
            visit.setVisitPeriod(visitDateStr + " " + timeSlotStr);
            System.out.println("构建的visitPeriod: " + visit.getVisitPeriod());
            
            // 如果maxNum为null，尝试从请求参数中直接获取（增加参数绑定的兼容性）
            if (visit.getMaxNum() == null) {
                System.out.println("直接从request获取的maxNumStr: " + maxNumStr);
                if (maxNumStr != null && !maxNumStr.isEmpty()) {
                    try {
                        visit.setMaxNum(Integer.parseInt(maxNumStr));
                        System.out.println("转换后的maxNum: " + visit.getMaxNum());
                    } catch (NumberFormatException e) {
                        System.out.println("maxNum转换失败: " + e.getMessage());
                        model.addAttribute("error", "新增失败: 可预约数量格式错误");
                        model.addAttribute("visit", visit);
                        model.addAttribute("departmentList", departmentService.findAll());
                        return "backend/visit/add";
                    }
                }
            }
            
            // 根据医生姓名查询医生信息
            if (visit.getDoctorName() != null && !visit.getDoctorName().isEmpty()) {
                Doctor doctor = doctorService.findByName(visit.getDoctorName());
                if (doctor != null) {
                    visit.setUserId(doctor.getDoctorId()); // 使用doctorId作为visit的userId
                    visit.setDeptId(doctor.getDeptId()); // 使用医生的科室ID
                    System.out.println("查询到的医生ID: " + doctor.getDoctorId());
                } else {
                    model.addAttribute("error", "新增失败: 找不到医生\"" + visit.getDoctorName() + "\"");
                    model.addAttribute("visit", visit);
                    model.addAttribute("departmentList", departmentService.findAll());
                    return "backend/visit/add";
                }
            } else {
                model.addAttribute("error", "新增失败: 医生姓名不能为空");
                model.addAttribute("visit", visit);
                model.addAttribute("departmentList", departmentService.findAll());
                return "backend/visit/add";
            }
            
            // 验证maxNum，确保它已经正确绑定
            if (visit.getMaxNum() == null || visit.getMaxNum() <= 0) {
                System.out.println("maxNum验证失败，当前值: " + visit.getMaxNum());
                model.addAttribute("error", "新增失败: 可预约数量必须大于0");
                model.addAttribute("visit", visit);
                model.addAttribute("departmentList", departmentService.findAll());
                return "backend/visit/add";
            }
            
            // 验证科室
            if (visit.getDeptId() == null) {
                model.addAttribute("error", "新增失败: 科室不能为空");
                model.addAttribute("visit", visit);
                model.addAttribute("departmentList", departmentService.findAll());
                return "backend/visit/add";
            }
            
            // 设置创建时间和初始已预约数量
            visit.setCreateTime(LocalDateTime.now());
            visit.setUsedNum(0);
            
            visitService.add(visit);
            return "redirect:find";
        } catch (Exception e) {
            e.printStackTrace(); // 打印完整异常堆栈
            model.addAttribute("error", "新增失败: " + e.getMessage());
            model.addAttribute("visit", visit);
            model.addAttribute("departmentList", departmentService.findAll());
            return "backend/visit/add";
        }
    }

    /**
     * 查询排班列表
     * 支持GET和POST请求方式，处理分页和条件查询
     * @param model 模型对象，用于传递数据到视图
     * @param pageNum 当前页码，默认为1
     * @param condition 查询条件对象
     * @return 排班列表页面的视图路径
     */
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      Visit condition) {
        int pageSize = 5;
        PageInfo<Visit> pageInfo = visitService.find(pageNum, pageSize, condition);
        
        // 处理数据，转换为JSP页面需要的格式
        List<Map<String, Object>> formattedVisits = new ArrayList<>();
        for (Visit visit : pageInfo.getList()) {
            Map<String, Object> formattedVisit = new HashMap<>();
            formattedVisit.put("visitId", visit.getVisitId());
            
            // 处理科室信息
            if (visit.getDepartment() != null) {
                formattedVisit.put("department", visit.getDepartment());
            }
            
            // 添加医生姓名
            formattedVisit.put("doctorName", visit.getDoctorName());
            
            // 处理排班日期和时段
            String visitPeriod = visit.getVisitPeriod();
            if (visitPeriod != null && visitPeriod.contains(" ")) {
                String[] parts = visitPeriod.split(" ", 2);
                formattedVisit.put("visitDate", parts[0]);
                formattedVisit.put("timeSlot", parts[1]);
            } else {
                formattedVisit.put("visitDate", "");
                formattedVisit.put("timeSlot", visitPeriod != null ? visitPeriod : "");
            }
            
            // 计算可预约数量和已预约数量 - 添加null值检查
            Integer maxNum = visit.getMaxNum() != null ? visit.getMaxNum() : 0;
            Integer usedNum = visit.getUsedNum() != null ? visit.getUsedNum() : 0;
            formattedVisit.put("availableCount", maxNum - usedNum);
            formattedVisit.put("bookedCount", usedNum);
            
            formattedVisits.add(formattedVisit);
        }
        
        // 创建新的PageInfo对象，替换列表数据
        PageInfo<Map<String, Object>> formattedPageInfo = new PageInfo<>(formattedVisits);
        formattedPageInfo.setPageNum(pageInfo.getPageNum());
        formattedPageInfo.setPageSize(pageInfo.getPageSize());
        formattedPageInfo.setTotal(pageInfo.getTotal());
        formattedPageInfo.setPages(pageInfo.getPages());
        
        model.addAttribute("pageInfo", formattedPageInfo);
        model.addAttribute("condition", condition);
        model.addAttribute("departmentList", departmentService.findAll());
        return "backend/visit/list";
    }

    /**
     * 根据ID查询排班详情（用于编辑）
     * 此方法合并了findById和edit两个路径的功能
     * @param visitId 排班ID
     * @param model 模型对象，用于传递数据到视图
     * @return 排班编辑页面的视图路径
     */
    @GetMapping({"/findById", "/edit"})
    public String findById(@RequestParam("visitId") Long visitId, Model model) {
        // 根据ID查询排班信息
        Visit visit = visitService.findById(visitId);
        if (visit == null) {
            visit = new Visit();
            visit.setVisitId(visitId);
        }
        model.addAttribute("visit", visit);
        model.addAttribute("departmentList", departmentService.findAll());
        return "backend/visit/edit";
    }

    /**
     * 修改排班信息
     * @param visit 包含更新信息的排班实体对象
     * @param model 模型对象，用于传递数据到视图
     * @return 成功则重定向到排班列表页面，失败则返回编辑页面
     */
    @PostMapping("/modify")
    public String modify(Visit visit, Model model) {
        try {
            // 添加日志记录
            System.out.println("====== 开始修改排班 ======");
            System.out.println("接收到的Visit对象: " + visit);
            System.out.println("visitDate值: " + visit.getVisitDate());
            System.out.println("timeSlot值: " + visit.getTimeSlot());
            
            // 验证并构建visitPeriod，与add方法保持一致
            if (visit.getVisitDate() != null && !visit.getVisitDate().isEmpty() && 
                visit.getTimeSlot() != null && !visit.getTimeSlot().isEmpty()) {
                // 构建完整的排班时段
                visit.setVisitPeriod(visit.getVisitDate() + " " + visit.getTimeSlot());
                System.out.println("构建的visitPeriod: " + visit.getVisitPeriod());
            }
            
            // 确保maxNum字段的正确绑定
            if (visit.getMaxNum() == null) {
                // 获取request对象
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                String maxNumStr = request.getParameter("maxNum");
                System.out.println("直接从request获取的maxNumStr: " + maxNumStr);
                if (maxNumStr != null && !maxNumStr.isEmpty()) {
                    try {
                        visit.setMaxNum(Integer.parseInt(maxNumStr));
                        System.out.println("转换后的maxNum: " + visit.getMaxNum());
                    } catch (NumberFormatException e) {
                        System.out.println("maxNum转换失败: " + e.getMessage());
                    }
                }
            }
            
            // 根据医生姓名查询医生ID
            if (visit.getDoctorName() != null && !visit.getDoctorName().isEmpty()) {
                User doctor = userService.findByUserName(visit.getDoctorName());
                if (doctor != null) {
                    visit.setUserId(doctor.getUserid());
                    System.out.println("查询到的医生ID: " + doctor.getUserid());
                }
            }
            
            visitService.modify(visit);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "修改失败: " + e.getMessage());
            model.addAttribute("visit", visit);
            model.addAttribute("departmentList", departmentService.findAll());
            return "backend/visit/edit";
        }
    }

    /**
     * 删除排班
     * @param visitId 排班ID
     * @return 重定向到排班列表页面
     */
    @GetMapping("/removeById")
    public String removeById(@RequestParam("visitId") Long visitId) {
        visitService.removeById(visitId); // 调用服务层删除指定ID的排班
        return "redirect:find"; // 重定向到排班列表页面
    }
}